<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 23/6/19
 * Time: 22:19
 */

namespace app\common\lib;

use think\Cache;

/**
 * IAuth 相关
 */
class IAuth
{
    /**
     * 设置密码
     * @param $data
     * @return string
     */
    public static function setPassword($data)
    {
        return md5($data . config('app.password_pre_halt'));
    }

    /**
     * 生成每次请求的sing
     * @param array $data
     * @return string
     */
    public static function serSing($data = [])
    {
        //1.安字段排序
        ksort($data);
        //2.拼接字符串数据
        $string = http_build_query($data);
        //3.通过aes加密
        $string = (new Aes())->encrypt($string);

        return $string;
    }

    /**
     * 检查sign是否正常
     * @param $data
     * @return bool
     */
    public static function checkSignPass($data)
    {
        $str = (new Aes())->decrypt($data['sign']);
        if (empty($str)) {
            return false;
        }
        parse_str($str, $arr);

        if (!is_array($arr) || empty($arr['did'])) {
            return false;
        }

        if (!config('app_debug')) {
            if ((time() - ceil($arr['time'] / 1000)) > config('app.app_sign_time')) {
                return false;
            }

            //唯一性判定

            if (Cache::get($data['sign'])) {
                return false;
            }
        }


        return true;

    }


    /**
     * 设置登陆的唯一Token
     * @param string $phone
     * @return string
     */
    public static function setAppLoginToken($phone = '')
    {
        $str = md5(uniqid(md5(microtime(true)), true));
        $str = sha1($phone . $str);
        return $str;
    }

}